import {
  Controller,
  Get,
  Post,
  Query,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { resumeOptimizeAI } from '../../utils/kimiAI';
import { Result } from 'src/components/Result';
import { Multer } from 'multer';
import * as fs from 'fs';
import * as path from 'path';
import { ResumeService } from '../resume/resume.service';

@Controller('ai')
export class AiController {
  constructor(private readonly resumeService: ResumeService) {}
  // 简历优化
  @Get('resumeOptimize')
  async resumeOptimizeAI(
    @Query('path') path: string,
    @Query('resumeId') resumeId: number,
  ) {
    // 调用你的 resumeOptimizeAI 函数
    const result = await resumeOptimizeAI(path);
    // 更新数据库中的优化结果
    await this.resumeService.update(resumeId, {
      optimizedResult: result || '',
    });
    return Result.success(result);
  }

  // 上传简历
  @Post('uploadResume')
  @UseInterceptors(FileInterceptor('file'))
  async uploadResume(@UploadedFile() file: Multer.File) {
    if (!file) {
      return Result.error('No file uploaded');
    }
    // 获取根目录下public的地址
    const rootDir = process.cwd();
    const uploadDir = path.join(rootDir, 'public', 'pdf');

    // 确保上传目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }

    // 处理文件名，使用Buffer进行编码
    // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
    const originalName = Buffer.from(file.originalname, 'latin1').toString(
      'utf8',
    );
    const timestamp = new Date().getTime();
    const fileName = `${timestamp}_${originalName}`;

    const filePath = path.join(uploadDir, fileName);
    // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
    fs.writeFileSync(filePath, file.buffer);

    // 保存简历文件信息到数据库
    const resume = {
      fileName: fileName,
      filePath: filePath,
      username: '小雨',
      fileType: 'pdf',
      optimizedResult: '',
    };
    const createdResume = await this.resumeService.create(resume);

    return Result.success({
      fileName: fileName,
      filePath: filePath,
      resumeId: createdResume.id,
    });
  }
}
